﻿using System;
using System.Reflection;
using System.Xml.Linq;

namespace NFox.Pycad.Root
{
    public class Application : PluginBase
    {

        public Application()
        {
            Root = this;
            Engine.SetPaths();

            //检查注册表，获取所有AutoCad版本
            foreach(var ver in AcadVersion.Versions)
            {
                if (ver.Number >= 2012)
                    ver.RegApp(
                        "NFox.Pycad",
                        Engine.MainPath.GetFile("NFox.Pycad.dll").FullName,
                        "NFox Pycad Loader");
            }

            string xml = Engine.SupportPath.GetFile("Config.xml")?.FullName;
            if (xml != null)
            {
                //读取插件树信息，并初始化
                var xe = XElement.Load(xml);
                Version = new Version(xe.Attribute("Version").Value);
                xe = xe?.Element(Name);
                if (xe != null)
                    LoadAndInit(this, xe);
            }
        }

        private void LoadAndInit(PluginBase plugin, XElement xe)
        {
            foreach (var e in xe.Elements())
            {
                var p = CreateSub(plugin, e);
                p?.Initialize();
            }
        }

        private PluginBase CreateSub(PluginBase plugin, XElement xe)
        {
            var path = DirectoryEx.GetFile($"{xe.Name}.dll")?.FullName;
            if (path != null)
            {
                Assembly ass = Assembly.LoadFrom(DirectoryEx.GetFile($"{xe.Name}.dll").FullName);
                Type t = ass.GetType($"{xe.Name}.Application");
                if (t != null)
                {
                    var p = (PluginBase)Activator.CreateInstance(t);
                    plugin.Add(p);
                    foreach (var e in xe.Elements())
                        CreateSub(p, e);
                    return p;
                }
            }
            return null;
        }

    }
}
